package de.dlrg.wms.controller.controllers;

import javassist.NotFoundException;

import javax.annotation.PostConstruct;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import wms2010.interfaces.devices.IDevice;

import de.dlrg.wms.controller.interfaces.ICRUD;
import de.dlrg.wms.dao.TrackDao;
import de.dlrg.wms.model.Track;

@Component
public class TrackController implements ICRUD<Track> {
	private HashMap<Long, Track> idTrackMapping = new HashMap<Long, Track>();
	@Autowired
	private TrackDao trackDao;
	
	public int getNextTrackNo() {
		int nextTrackNo = 1;
		for(Track track : this.readAll()) {
			if(track.getTrackNumber()>nextTrackNo) {
				nextTrackNo = track.getTrackNumber();
			}
		}
		return nextTrackNo + 1;
	}
	
	public List<Track> readAll() {
		List<Track> availableTracks = new ArrayList<Track>(this.idTrackMapping.values());
		return availableTracks;
	}

	public void createOrUpdate(Track toCreateOrUpdate) {
		this.validate(toCreateOrUpdate);
		Track dbTrack = this.trackDao.save(toCreateOrUpdate);
		toCreateOrUpdate.setId(dbTrack.getId());
		if(this.idTrackMapping.containsKey(toCreateOrUpdate.getId())) {
			// update
			this.idTrackMapping.remove(toCreateOrUpdate.getId());
			this.idTrackMapping.put(toCreateOrUpdate.getId(), toCreateOrUpdate);
		} else {
			// create
			this.idTrackMapping.put(toCreateOrUpdate.getId(), toCreateOrUpdate);
		}
	}

	public void delete(Track toDelete) {
		this.trackDao.delete(toDelete);
		this.idTrackMapping.remove(toDelete.getId());
	}

	public void validate(Track toValidate) {
		// TODO Auto-generated method stub
		
	}

	public Track getTrackByDevice(IDevice device) {
		for(Track track : this.readAll()) {
			if(track.getStopperDevice().equals(device)) {
				return track;
			}
		}
		return null;
	}
	
	@PostConstruct
	public void postConstruct() {
		for(Track track : this.trackDao.readAll()) {
			this.idTrackMapping.put(track.getId(), track);
		}
		System.out.println("initialized idmap of tracks");
	}

	public Long getTotalCount() {
		return this.trackDao.count();
	}
}
